import { getLogo, getSystemInfo } from "@/api/system";
import defaultSettings from "@/settings";
import { commitData } from "@/utils/util";

const { sideTheme, topNav, theme, fontColor } = defaultSettings;

const state = {
  companyName: "", //企业名称
  systemName: "", //系统名称
  copyrightInfo: "", //版权信息
  theme: "#409eff", //平台主题
  sideTheme: "", //侧边主题 深色/浅色
  topNav: "", //导航模式 侧边/顶部/混合
  logo: null,
  logoType: "0", //logo类型 0纯logo 1图文logo
  colorValue: "", //字体颜色
  isThird: false, //是否启用三方系统集成
  isSelfAdapt: false, //系统标题自适应
};
const mutations = {
  SET_INFO: (state, info) => {
    if (info) {
      state.companyName = info.companyName || "";
      state.systemName = info.systemName || "";
      state.copyrightInfo = info.copyrightInfo || "";
      state.logoType = info.logoType || "0";
      state.isThird = info.isThird || false;
      state.isSelfAdapt = info.isSelfAdapt || false;
    } else {
      state.companyName = "";
      state.systemName = "";
      state.copyrightInfo = "";
      state.logoType = "0";
      state.isThird = false;
      state.isSelfAdapt = false;
    }
  },
  SET_FONT_COLOR: (state, colorValue) => {
    state.colorValue = colorValue || fontColor;
  },
  SET_THEME: (state, themeValue) => {
    state.theme = "#409eff" || themeValue || theme;
  },
  SET_SIDE_THEME: (state, sideThemeValue) => {
    state.sideTheme = sideThemeValue || sideTheme;
  },
  SET_TOP_NAV: (state, topNavValue) => {
    state.topNav = topNavValue || topNav;
  },
  SET_LOGO: (state, logo) => {
    state.logo = logo;
  },
};

const actions = {
  setSystemInfo({ commit }) {
    getSystemInfo()
      .then((res) => {
        if (res && res.code === 200) {
          try {
            let info = JSON.parse(res.data);

            commit("SET_INFO", {
              companyName: info.companyName,
              systemName: info.systemName,
              copyrightInfo: info.copyrightInfo,
              logoType: info.logoType,
              isThird: info.isThird,
              isSelfAdapt: info.isSelfAdapt,
            });

            commit("SET_THEME", info.theme);
            commit("SET_SIDE_THEME", info.sideTheme);
            commit("SET_TOP_NAV", info.topNav);
            commit("SET_FONT_COLOR", info.fontColor);

            // document.title = info.systemName;
          } catch (e) {
            commit("SET_INFO");
            commitData(commit);
          }
        } else {
          commit("SET_INFO");
          commitData(commit);
        }
      })
      .catch((err) => {
        commit("SET_INFO");
        commitData(commit);
      });
  },
  setLogo({ commit }) {
    getLogo()
      .then((res) => {
        if (res && res.code === 200) {
          commit("SET_LOGO", `data:image/png;base64,${res.data}`);
        } else {
          commit("SET_LOGO", null);
        }
      })
      .catch((err) => {
        commit("SET_LOGO", null);
      });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
